package edu.scau.mis.rest.service.impl;

import edu.scau.mis.core.redis.RedisCache;
import edu.scau.mis.rest.entity.RestItem;
import edu.scau.mis.rest.entity.RestOrder;
import edu.scau.mis.rest.entity.RestOrderItem;
import edu.scau.mis.rest.entity.RestUser;
import edu.scau.mis.rest.entity.vo.RestOrderVo;
import edu.scau.mis.rest.mapper.*;
import edu.scau.mis.rest.service.RestOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * (RestOrder)表服务实现类
 *
 * @author makejava
 * @since 2022-03-16 11:17:52
 */
@Service("restOrderService")
public class RestOrderServiceImpl implements RestOrderService {
    @Resource
    private RestOrderMapper restOrderMapper;

    @Autowired
    RedisCache redisCache;

    @Autowired
    RestSeatMapper restSeatMapper;

    @Autowired
    RestUserMapper restUserMapper;

    @Autowired
    RestOrderItemMapper restOrderItemMapper;

    @Autowired
    RestItemMapper restItemMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public RestOrder queryById(Long id) {
        return this.restOrderMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param restOrder 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<RestOrder> queryByPage(RestOrder restOrder, PageRequest pageRequest) {
        long total = this.restOrderMapper.count(restOrder);
        return new PageImpl<>(this.restOrderMapper.queryAllByLimit(restOrder, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param restOrder 实例对象
     * @return 实例对象
     */
    @Override
    public RestOrder insert(RestOrder restOrder) {
        this.restOrderMapper.insert(restOrder);
        return restOrder;
    }

    /**
     * 修改数据
     *
     * @param restOrder 实例对象
     * @return 实例对象
     */
    @Override
    public RestOrder update(RestOrder restOrder) {
        this.restOrderMapper.update(restOrder);
        return this.queryById(restOrder.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.restOrderMapper.deleteById(id) > 0;
    }

    /**
     * 插入订单
     *
     * @param openid
     * @return
     */
    @Override
    public int insertOrder(String openid){
        /**获取总价**/
        BigDecimal totalAmount = new BigDecimal(redisCache.getListByIndex(openid, 2).toString());

        /**获取餐位id**/
        //获取餐桌号
        String seatNo = redisCache.getListByIndex(openid, 1).toString();
        //获取餐位id
        long seatId = restSeatMapper.querySeatBySeatNo(seatNo).getId();


        /**生成订单证号**/
        //获取当日时间
        String fotmatTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //利用java自带的uuid随机生成字符串，去掉头尾的空格和'-'字符, 保留六个字符
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "").substring(0, 6);
        //拼接数据
        String orderNo = "so_" + fotmatTime + "_" + uuid;

        /**设置当前时间**/
        Date currentTime = new Date();

        /**获取产品总数**/
        int itemNum = 0;
        int totalQuantity = 0;
        String seat = redisCache.getListByIndex(openid, 0).toString();
        for(long i = 0; i < redisCache.getListLength(seat); i++){
            itemNum = ((RestItem) redisCache.getListByIndex(seat, i)).getNum();
            totalQuantity = itemNum + totalQuantity;
        }

        /**获取用户id**/
        long userId = restUserMapper.queryRestUserByOpenid(openid).getId();

        RestOrder restOrder = new RestOrder();
        restOrder.setOrderNo(orderNo);
        restOrder.setSaleTime(currentTime);
        restOrder.setSeatId(seatId);
        restOrder.setTotalAmount(totalAmount);
        restOrder.setTotalQuantity(totalQuantity);
        restOrder.setUserId(userId);

        int result = this.restOrderMapper.insert(restOrder);

        //缓存orderNo
        redisCache.addList(openid, restOrder.getId());

        return result;
    }

    /**
     * 通过订单证号查询订单
     *
     * @param orderNo
     * @return
     */
    @Override
    public RestOrder queryOrderByOrderNo(String orderNo){return this.restOrderMapper.queryOrderByOrderNo(orderNo);}

    /**
     * 获取本次就餐订单
     *
     * @param openid
     * @return
     */
    @Override
    public RestOrderVo getNowOrder(String openid){

        /**获取餐位证号**/
        String seatNo = redisCache.getListByIndex(openid, 1).toString();

        /**获取总价**/
        BigDecimal totalAmount = (BigDecimal) redisCache.getListByIndex(openid, 2);

        /**获取订单基本信息**/
        long orderId = (long)redisCache.getListByIndex(openid, 3);
        RestOrder restOrder = restOrderMapper.queryById(orderId);
        String orderNo = restOrder.getOrderNo();
        Date saleTime = restOrder.getSaleTime();

        /**获取餐品列表**/
        List<RestItem> restItemList = redisCache.getCacheList(redisCache.getListByIndex(openid, 0).toString());

        /**转换时间格式**/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(saleTime);

        RestOrderVo restOrderVo = new RestOrderVo();
        restOrderVo.setOrderNo(orderNo);
        restOrderVo.setSaleTime(dateString);
        restOrderVo.setTotalAmount(totalAmount);
        restOrderVo.setOrder(restItemList);
        restOrderVo.setSeatNo(seatNo);

        return restOrderVo;
    }

    /**
     * 获取用户所有订单
     *
     * @param openid
     * @return
     */
    @Override
    public List<RestOrderVo> getMyOrder(String openid){

        //获取用户id
        long userId = restUserMapper.queryRestUserByOpenid(openid).getId();
        //获取所有订单
        List<RestOrder> restOrderList = restOrderMapper.queryOrderByUserId(userId);

        /**转换时间格式**/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<RestOrderVo> restOrderVoList = new ArrayList<>();

        for(int i = 0; i < restOrderList.size(); i++){
            RestOrderVo restOrderVo = new RestOrderVo();
            restOrderVo.setOrderNo(restOrderList.get(i).getOrderNo());
            restOrderVo.setSaleTime(simpleDateFormat.format(restOrderList.get(i).getSaleTime()));
            restOrderVo.setTotalAmount(restOrderList.get(i).getTotalAmount());

            String seatNo = restSeatMapper.queryById(restOrderList.get(i).getSeatId()).getSeatNo();
            restOrderVo.setSeatNo(seatNo);

            List<RestOrderItem> restOrderItemList = restOrderItemMapper.queryOrderItemByOrderId(restOrderList.get(i).getId());
            List<RestItem> restItemList = new ArrayList<>();
            for(int j = 0; j < restOrderItemList.size(); j++){
                RestItem restItem = restItemMapper.queryById(restOrderItemList.get(j).getItemId());
                restItem.setSaleAmount(restOrderItemList.get(j).getSaleAmount());
                restItem.setNum(restOrderItemList.get(j).getSaleQuantity());
                restItemList.add(restItem);
            }
            restOrderVo.setOrder(restItemList);

            restOrderVoList.add(restOrderVo);
        }

        return restOrderVoList;
    }

    /**
     * 清除缓存
     *
     * @param openid
     */
    @Override
    public void clearCache(String openid){
        //获取餐位的key
        String seat = redisCache.getListByIndex(openid, 0).toString();
        //获取餐位号
        String seatNo = redisCache.getListByIndex(openid, 1).toString();

        //清空缓存
        redisCache.deleteObject(seat);
        redisCache.deleteObject(openid);
    }

    /**
     * 根据openid获取用户所有订单
     *
     * @param openid
     * @return
     */
    @Override
    public List<RestOrder> getNowOrderByOpenid(String openid){
        RestUser restUser = restUserMapper.queryRestUserByOpenid(openid);
        return this.restOrderMapper.queryNowOrderByUserId(restUser.getId());
    }
}
